extends Node2D

@onready var tileMap = $TileMap
@onready var camera = $Camera2D
var STONE = Vector2i(1,0)
var AIR   = Vector2i(1,1)
var WATER = Vector2i(0,1)
var GREEN = Vector2i(0,0)

var noise = FastNoiseLite.new()
# 密度噪声
var densityNoise = FastNoiseLite.new()
# 条状洞穴
var caveNoise = FastNoiseLite.new()

# Called when the node enters the scene tree for the first time.
func _ready():
	noise.seed = randi()
	densityNoise.seed = randi()
	caveNoise.seed = randi()
	#
	#for x in range(0,10000):
		#for y in range(0,10000):
			#if x == 0: tileMap.set_cell(0,Vector2(x,y),0,STONE,TileSetAtlasSource.TRANSFORM_FLIP_V)
			#if y == 0:tileMap.set_cell(0,Vector2(x,y),0,GREEN,TileSetAtlasSource.TRANSFORM_FLIP_V)
			
			
	for x in range(-100,1000):
		for y in range(-1000,100):
			tileMap.set_cell(0,Vector2(x,y),0,getBlock(x,y),TileSetAtlasSource.TRANSFORM_FLIP_V)




func getBlock(x, y) -> Vector2i:
	var noi = noise.get_noise_1d(x)
	var caveNoi = caveNoise.get_noise_2d(x,y)
	
	var baseHeight = caculateHeight(noi)
	var surfaceY = baseHeight + noise.get_noise_1d(x)*30

	if (y < surfaceY):   
		#print("%d,%d" % [y,surfaceY])
		return STONE
		
		
		#if(y < surfaceY -20 && y > surfaceY-80 && caveNoi < 0.15 && caveNoi > -0.15): return AIR
		#else: return STONE
	else: return AIR
	
	
	
	#密度噪声
	#return STONE if densityNoi > -0.3 else AIR
	
	
	

func caculateHeight(noi):
	#if 	  noi < 0.3: return calLinearEqa(-1,50,0.3,100,noi)
	#elif  noi < 0.4: return calLinearEqa(0.3,100,0.4,120,noi)
	#else: return 120
	return -10
	
func getRandomBool() -> bool:
	var randomInt = randi() % 2  # 生成 0 或 1 的随机整数
	var randomBool = randomInt == 1  # 将随机整数转换为布尔类型值
	return randomBool

func perlin_noise_1d(x: float, frequency: float, _amplitude: float, lacunarity: float, persistence: float, octaves: int) -> float:
	var total = 0.0
	var max_value = 0.0
	var amplitude_accumulator = 1.0

	for i in range(octaves):
		total += noise_1d(x * frequency) * amplitude_accumulator
		max_value += amplitude_accumulator
		frequency *= lacunarity
		amplitude_accumulator *= persistence

	return total / max_value

func noise_1d(x: float) -> float:
	return noise.get_noise_1d(x)


func calLinearEqa(x1,y1,x2,y2,x):
	var slope = (y2 - y1) / (x2 - x1)
	return slope * (x - x1) + y1


